const serialPortElement = document.getElementById('serial_port_select');
const searchSerialPort = document.getElementById('search_serial_port');
const targetFileElement = document.getElementById('target_file');
const serialPortDownload = document.getElementById('serial_port_download');

// 搜索串口单击事件
searchSerialPort.addEventListener('click', async () => {
    // 从预加载脚本查询可用串口
    const availablePorts = await window.serialAPI.listSerialPorts();

    // 清空并重新添加页面 <select> 的选项
    serialPortElement.length = 0
    for (let port of availablePorts) {
        serialPortElement.options.add(new Option(port.friendlyName, port.path))
    }
});

// 目标文件的单击事件
targetFileElement.addEventListener('click', async () => {
    targetFileElement.value = await window.serialAPI.chooseTargetFile();
})


function getDevice() {
    const targetDevice = document.getElementsByName('target_device');
    for (let option of targetDevice) {
        if (option.checked) {
            return option.value;
        }
    }
    return undefined
}

// 发送串口数据
serialPortDownload.addEventListener('click', async () => {
    let serialConfig = {
        com: serialPortElement.options[serialPortElement.selectedIndex].value,
        targetFilePath: targetFileElement.value,
        deviceType: getDevice()
    }

    console.log(serialConfig)

    await window.serialAPI.sendSerialPortData(serialConfig);
})
